var app = getApp();
var util = require('../../utils/util.js');
Page({
  data: {
    //当前展示页
    pageIndex: 1,
    //喵文列表
    time: '',
    talkList: [],
    talkList1: [],
    talkList2: [],
    //下拉刷新
    refresh: false,
    //喵文发布类型是否隐藏
    talkTypeHidden: true,
    //获取用户信息:单按钮提示框隐藏
    userInfoAuthHidden: true,
    //获取用户信息:单按钮提示
    userInfoAuthContent: '请求获取您的公开信息(头像,昵称)',
    //登录失败:单按钮提示
    loginErrContent: '',
    //登录失败:单按钮提示框隐藏
    loginErrHidden: true,
    //转发进入
    share: null,
    //socket上下文
    socketTask: null,
    scrollTop1: 0,
    scrollTop2: 0,
    //新粉丝小红点
    fansDot: true,
    //新点赞小红点
    likeDot: true,
    //新评论小红点
    commentDot: true,
    //用户信息
    user: null,
    //宠物列表
    petList: [],
    //没有地理位置
    locationErrHidden: true,
    //送养列表
    giveList: [],
    giveList1: [],
    giveList2: [],
    //聊天列表
    chat: [],
    chatDot: true,
    //用户喵文记录
    userTalkList: [],
    userTalkList1: [],
    userTalkList2: [],
    //当前是日志还是送养
    mySel: 1,
    //送养记录
    userGiveList: [],
    userGiveList1: [],
    userGiveList2: [],
    //商品列表
    goodsList: [],
    //侧边栏展开收起
    flankHidden: true
  },



  onLoad: function(options) {
    //如果是转发,则保存转发信息
    if (options.share) {
      this.data.share = JSON.parse(options.share)
    }

    //获取喵文列表
    this.getTalk();

    //获取用户权限
    this.userInfoAuth();
    //找到系统状态位置
    var systemInfo = app.globalData.systemInfo;
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight + 5,
      windowHeight: systemInfo.windowHeight,
      screenHeight: app.globalData.systemInfo.screenHeight
    })

    //发布动画
    this.data.animation = wx.createAnimation({});
    //监听socket连接成功事件
    this.socketOpen();
    //监听socket连接关闭
    this.socketClose();
    //发送socket心跳包
    this.setHeartbeat();
    //监听服务端发送消息
    this.socketMessage();
    //商品列表
    this.getGoodsList();
    //送养列表
    this.getGivePetListByCity();
  },


  //页面隐藏
  onHide: function() {
    var pageIndex = this.data.pageIndex;
    //如果在发布页,则隐藏发布类型
    if (pageIndex == 3) {
      this.setData({
        talkTypeHidden: true
      })
    }
  },
  //上拉触底
  onReachBottom: function() {
    var pageIndex = this.data.pageIndex;
    if (pageIndex == 1) {
      var talkList = this.data.talkList;
      //拿到最后一个喵文的时间
      this.data.time = talkList[talkList.length - 1].talkDate;
      this.getTalk();
    } else if (pageIndex == 4) {
      var chat = this.data.chat;
      var time = chat[chat.length - 1].messageDate;
      this.getUserChatList(time);
    }
  },
  //下拉刷新
  onPullDownRefresh: function() {
    var pageIndex = this.data.pageIndex;
    if (pageIndex == 1) {
      this.data.refresh = true;
      this.data.time = '';
      this.getTalk();
    }
  },
  //页面进入
  onShow: function() {
    this.socketMessage();
    this.setData({
      randomNumber: Math.random(),
      petList: app.globalData.petList,
      chat: app.globalData.chat,
      user: app.globalData.user,
      flankHidden:true
    })
  },
  //页面滚动
  onPageScroll: function(e) {
    var pageIndex = this.data.pageIndex;
    if (pageIndex == 1) {
      this.data.scrollTop2 = this.data.scrollTop1;
      this.data.scrollTop1 = e.scrollTop;
    } else if (pageIndex == 5) {
      if (!this.data.flankHidden) {
        return;
      }
    }
  },
  //建立socket连接
  openMySocket: function() {
    var that = this;
    this.data.socketTask = wx.connectSocket({
      url: app.globalData.wsUrl
    })
  },
  //监听socket连接成功事件
  socketOpen: function() {
    var that = this;
    wx.onSocketOpen(function() {
      //连接成功后,发送自己的id到服务器
      var message = {
        type: 'sendId',
        data: app.globalData.user.id
      }
      that.data.socketTask.send({
        data: JSON.stringify(message),
        success: function() {
          wx.request({
            url: app.globalData.requestUrl + 'getAllMessage',
            method: 'GET',
            data: {
              userId: app.globalData.user.id
            }
          })
        }
      })
    })
  },
  //监听客户端发送消息
  socketMessage: function() {
    var that = this;
    wx.onSocketMessage(function(r) {
      var message = JSON.parse(r.data);
      var key = Object.keys(message)[0];
      if (key == 1) {
        wx.showToast({
          title: '您编辑的日志已成功发布,请前往个人中心查看.',
          icon: 'none',
          duration: 3000
        })
        that.setData({
          refresh: true
        })
        //获取用户日志记录~
        that.getTalkListByUserId();
      } else if (key == 2) {
        //点赞通知
        var count = message[2];
        if (count != 0) {
          that.setData({
            likeDot: false
          })
        }
      } else if (key == 3) {
        //新粉丝通知
        var count = message[3];
        if (count != 0) {
          that.setData({
            fansDot: false
          })
        }
      } else if (key == 4) {
        //新评论个数
        var count = message[4];
        if (count != 0) {
          that.setData({
            commentDot: false
          })
        }
      } else if (key == 9) {
        wx.showToast({
          title: '您编辑的送养信息已成功发布.',
          icon: 'none',
          duration: 3000
        })
        that.setData({
          refresh: true
        })
        //获取用户送养记录
        that.getGiveListByUserId();
        wx.clearStorage("addGivePet");
      } else if (key == 'putChat') {
        var chat = message[key];
        for (var i of app.globalData.chat) {
          if (i.id == chat.id) {
            i.chatList.unshift(chat);
            i.dot = false;
            break;
          }
        }
        that.setData({
          chat: app.globalData.chat,
          chatDot: false
        })
      } else if (key == 'addChat') {
        var chat = message[key];
        chat.dot = false;
        app.globalData.chat.unshift(chat);
        that.setData({
          chat: app.globalData.chat,
          chatDot: false
        })
      }
    })
  },

  //发送心跳包
  setHeartbeat: function() {
    //5分钟向后端发送一次心跳
    var that = this;
    setInterval(function() {
      var socketTask = that.data.socketTask;
      if (socketTask != null) {
        var message = {
          type: 'sendId',
          data: app.globalData.user.id
        }
        that.data.socketTask.send({
          data: JSON.stringify(message)
        })
      }
    }, 1000 * 60 * 5)
  },

  //监听socket连接关闭
  socketClose: function() {
    var that = this;
    wx.onSocketClose(function() {
      //失败重连
      that.socketOpen();
    })
  },
  //获取用户聊天列表
  getUserChatList: function(time) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getUserChatList',
      data: {
        userId: app.globalData.user.id,
        time: time
      },
      method: 'POST',
      success: function(r) {
        if (r.data.code == 200) {
          var chat = r.data.data;
          for (var i of chat) {
            if (i.isRead == 1) {
              i.dot = true;
            } else {
              that.setData({
                chatDot: false
              })
              i.dot = false;
            }

          }
          app.globalData.chat = app.globalData.chat.concat(chat);
          that.setData({
            chat: app.globalData.chat
          })
        } else {
          wx.showToast({
            title: '获取聊天记录出现了点问题.',
            icon: 'none',
            duration: 30000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,获取聊天记录失败',
          icon: 'none',
          duration: 30000
        })
      }
    })
  },

  //获取送养列表
  getGivePetListByCity: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getGivePetListByCity',
      method: 'POST',
      data: {
        city: null,
        time: null
      },
      success: function(r) {
        if (r.data.code == 200) {
          var data = r.data.data.slice(0, 4);
          //左边数组
          var arr1 = [];
          //右边数组
          var arr2 = [];
          for (var i = 0; i < data.length; i++) {
            //找到图片高度
            data[i].imageHeight = util.getImageHeight(data[i].height, data[i].width, 0.48);
            data[i].talkType = 0;

            //如果是双数则放到第一个盒子
            if (i % 2 == 0) {
              arr1.push(data[i]);
            } else {
              arr2.push(data[i]);
            }
          }
          //如果是下拉则清空
          if (that.data.refresh) {
            that.setData({
              giveList: data,
              giveList1: arr1,
              giveList2: arr2,
              refresh: false
            })
            wx.stopPullDownRefresh();
          } else {
            if (data.length == 0) {} else {
              that.setData({
                giveList: that.data.giveList.concat(data),
                giveList1: that.data.giveList1.concat(arr1),
                giveList2: that.data.giveList2.concat(arr2)
              })
            }
          }
        } else {
          wx.showToast({
            title: '获取送养信息失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,获取送养信息失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },


  //获取聊天记录
  chatInfo: function(e) {
    var index = e.currentTarget.dataset.index;
    var id = this.data.chat[index].id;
    this.data.chat[index].dot = true;
    var dotL = 0;
    for (var i of this.data.chat) {
      if (i.dot) {
        dotL = dotL + 1;
      } else {
        break;
      }
    }
    if (dotL == this.data.chat.length) {
      this.setData({
        chatDot: true
      })
    }
    wx.navigateTo({
      url: '/pages/chatInfo/chatInfo?id=' + id
    })
  },
  //喵文列表
  getTalkListByUserId: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getTalkListByUserId',
      data: {
        userId: app.globalData.user.plainText
      },
      success: function(r) {
        if (r.data.code == 200) {
          var data = r.data.data;
          //左边数组
          var arr1 = [];
          //右边数组
          var arr2 = [];
          for (var i = 0; i < data.length; i++) {
            if (data[i].talkType != 0) {
              data[i].src = data[i].src + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_" + data[i].width + ",h_" + data[i].height + ",m_fast";
            }
            //找到图片高度
            data[i].imageHeight = util.getImageHeight(data[i].height, data[i].width, 0.48);
            data[i].talkType = 0;

            //如果是双数则放到第一个盒子
            if (i % 2 == 0) {
              arr1.push(data[i]);
            } else {
              arr2.push(data[i]);
            }
          }
          //如果是下拉则清空
          if (that.data.refresh) {
            that.setData({
              userTalkList: data,
              userTalkList1: arr1,
              userTalkList2: arr2,
              refresh: false
            })
            wx.stopPullDownRefresh();
          } else {
            if (data.length == 0) {

            } else {
              that.setData({
                userTalkList: that.data.userTalkList.concat(data),
                userTalkList1: that.data.userTalkList1.concat(arr1),
                userTalkList2: that.data.userTalkList2.concat(arr2)
              })
            }
          }
        } else {
          wx.showToast({
            title: '获取日志记录失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,获取日志记录失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },
  //用户送养记录
  getGiveListByUserId: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getGiveListByUserId',
      data: {
        userId: app.globalData.user.plainText
      },
      success: function(r) {
        if (r.data.code == 200) {
          var data = r.data.data;
          //左边数组
          var arr1 = [];
          //右边数组
          var arr2 = [];
          for (var i = 0; i < data.length; i++) {
            //找到图片高度
            data[i].imageHeight = util.getImageHeight(data[i].height, data[i].width, 0.48);
            data[i].talkType = 0;

            //如果是双数则放到第一个盒子
            if (i % 2 == 0) {
              arr1.push(data[i]);
            } else {
              arr2.push(data[i]);
            }
          }
          //如果是下拉则清空
          if (that.data.refresh) {
            that.setData({
              userGiveList: data,
              userGiveList1: arr1,
              userGiveList2: arr2,
              refresh: false
            })
            wx.stopPullDownRefresh();
          } else {
            if (data.length == 0) {

            } else {
              that.setData({
                userGiveList: that.data.userGiveList.concat(data),
                userGiveList1: that.data.userGiveList1.concat(arr1),
                userGiveList2: that.data.userGiveList2.concat(arr2)
              })
            }
          }
        } else {
          wx.showToast({
            title: '获取送养记录失败',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,获取送养记录失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },

  //获取宠物列表
  getAllPetByUserId: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getAllPetByUserId',
      data: {
        userId: app.globalData.user.id
      },
      success: function(r) {
        if (r.data.code == 200) {
          var petList = r.data.data;
          app.globalData.petList = petList;
          that.setData({
            petList: petList
          })
        } else {
          wx.showToast({
            title: '获取宠物资料失败,请稍后重试',
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,获取宠物资料失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },

  /*用户登录 */
  userLogin: function() {
    var that = this;
    //同步获取缓存用户id
    var userId = wx.getStorageSync("userId");
    //缓存中拿不到userid
    if (userId == '') {
      //获取用户登录凭证 code
      wx.login({
        success: function(res) {
          that.getUser('', res.code);
        },
        fail: function(res) {
          //获取code失败
          that.setData({
            loginErrHidden: false,
            loginErrContent: '获取微信code失败,尝试重新连接'
          })
        }
      })
    } else {
      //缓存中取到用户id
      that.getUser(userId, '');
    }
  },




  /*发起请求获取用于id
   */
  getUser: function(userId, code) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getUserInfo',
      method: 'GET',
      data: {
        id: userId,
        code: code
      },
      success: function(res) {
        var user = res.data.data;
        //如果状态是200 说明返回的有用户对象
        if (res.data.code == 200) {
          //设置全局用户对象
          app.globalData.user = user;
          //设置用户id缓存
          wx.setStorage({
            key: 'userId',
            data: user.id,
          })
          //刷新用户
          that.refreshUser();
          //更改头像昵称地理位置
          that.updateUserMessage();
          //获取宠物
          that.getAllPetByUserId();
          //获取聊天记录
          that.getUserChatList(null);
          //获取用户日志记录~
          that.getTalkListByUserId();
          //获取用户送养记录
          that.getGiveListByUserId();
          //获取用户购物车商品
          that.getShoppingCarList();
        } else {
          //清除用户缓存
          wx.clearStorage("userId");
          that.userInfoAuth();
        }
      },
      fail: function() {
        //获取code失败
        that.setData({
          loginErrHidden: false,
          loginErrContent: '网络连接失败,请重试'
        })
      }
    })
  },

  //跳转送养
  addGivePet: function() {
    var user = this.data.user;
    console.log(user)
    if (user.province == null) {
      this.setData({
        locationErrHidden: false
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/addGivePet/addGivePet',
    })
  },


  //获取用户权限
  userInfoAuth: function() {
    var that = this;
    wx.getSetting({
      success: function(r) {
        var authSessing = r.authSetting;
        if (authSessing['scope.userInfo']) {
          wx.getUserInfo({
            success: function(e) {
              that.setData({
                userInfo: e.userInfo
              })
              //用户登录
              that.userLogin();
            }
          })
        } else {
          that.setData({
            userInfoAuthHidden: false
          })
        }
      }
    })
  },

  //获取用户信息
  getUserInfo: function(e) {
    var that = this;
    if (e.detail.detail.errMsg == 'getUserInfo:ok') {
      this.setData({
        userInfoAuthHidden: true,
        userInfo: e.detail.detail.userInfo
      })
      //用户登录
      that.userLogin();
    }
  },

  //刷新用户信息
  refreshUser: function() {
    var user = app.globalData.user;
    user.showConcernQuantity = util.formatQuantity(user.concernQuantity);
    user.showFansQuantity = util.formatQuantity(user.fansQuantity);
    user.showLikeQuantity = util.formatQuantity(user.likeQuantity);
    this.setData({
      user: user
    })
  },
  //跳转修改资料
  updateUserNav: function() {
    wx.navigateTo({
      url: '/pages/userInfo/userInfo',
    })
  },
  //更改用户资料
  updateUserMessage: function() {
    var that = this;
    //用户头像昵称
    var userInfo = this.data.userInfo;
    wx.request({
      url: app.globalData.requestUrl + 'updateUserAddress',
      method: 'POST',
      data: {
        id: app.globalData.user.id,
        nikeName: userInfo.nickName,
        headPortrait: userInfo.avatarUrl,
      },
      success: function(r) {
        if (r.data.code == 200) {
          app.globalData.user = r.data.data
          //跳转转发页
          that.shareSkip();
          //建立socket连接
          that.openMySocket();
          //刷新用户
          that.refreshUser();
        } else {
          wx.showToast({
            title: r.data.message,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络连接错误,更新用户信息失败',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },

  //跳转搜索
  searchPage: function() {
    var user = app.globalData.user;
    if (user == null) {
      wx.showToast({
        title: '正在登陆',
        icon: 'loading',
        duration: 1000
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/searchTalk/searchTalk',
    })
  },

  //跳转主页
  skipIndex: function() {
    var pageIndex = this.data.pageIndex;
    if (pageIndex != 1) {
      var scrollTop = this.data.scrollTop2;
      this.setData({
        pageIndex: 1
      })
      this.go(scrollTop);
    }

  },
  //pageScrollTo bug 需要定义一个专门的方法才可以跳转
  go: function(scrollTop) {
    wx.pageScrollTo({
      scrollTop: scrollTop,
      duration: 0
    })
  },
  //日志 送养切换
  selMyPush: function(e) {
    var type = e.currentTarget.dataset.type;
    if (this.data.mySel == type) {
      return;
    } else {
      this.setData({
        mySel: type
      })
    }
  },



  //跳转发现
  skipFind: function() {
    var user = app.globalData.user;
    if (user == null) {
      wx.showToast({
        title: '正在登陆',
        icon: 'loading',
        duration: 1000
      })
      return;
    }
    var pageIndex = this.data.pageIndex;
    if (pageIndex != 2) {
      var scrollTop = this.data.scrollTop4;
      this.setData({
        pageIndex: 2
      })
      this.go(scrollTop);
    }
  },
  //跳转详情
  showTalk: function(e) {
    var user = app.globalData.user;
    if (user == null) {
      wx.showToast({
        title: '正在登陆',
        icon: 'loading',
        duration: 1000
      })
      return;
    }
    var id = e.detail.currentTarget.dataset.id;
    var type = e.detail.currentTarget.dataset.type;
    if (type == '') {
      wx.navigateTo({
        url: '/pages/talkInfo/talkInfo?id=' + id
      })
    } else if (type == 'give') {
      wx.navigateTo({
        url: '/pages/giveInfo/giveInfo?id=' + id,
      })
    }

  },


  //跳转发布
  skipHello: function() {
    var user = app.globalData.user;
    if (user == null) {
      wx.showToast({
        title: '正在登陆',
        icon: 'loading',
        duration: 1000
      })
      return;
    }
    var that = this;
    var pageIndex = this.data.pageIndex;
    if (pageIndex != 3) {
      this.setData({
        pageIndex: 3
      })
      //喵文动画
      var animation = this.data.animation;
      animation.translateY(-20).step({
        duration: 200
      });
      this.setData({
        pushTypeTalkAnimation: animation.export()
      })
      //设置定时器恢复页面
      var timeout1 = setTimeout(function() {
        animation.translateY(20).step({
          duration: 200
        });
        that.setData({
          pushTypeTalkAnimation: animation.export()
        })
        clearTimeout(timeout1);
      }, 200)

      //送养动画
      animation.translateY(-20).step({
        duration: 200,
        delay: 100
      });
      this.setData({
        pushTypeGiveAnimation: animation.export()
      })
      //设置定时器恢复页面
      var timeout2 = setTimeout(function() {
        animation.translateY(20).step({
          duration: 300
        });
        that.setData({
          pushTypeGiveAnimation: animation.export()
        })
        clearTimeout(timeout2);
      }, 200)
    }
  },
  //跳转消息
  skipMessage: function() {
    var user = app.globalData.user;
    if (user == null) {
      wx.showToast({
        title: '正在登陆',
        icon: 'loading',
        duration: 1000
      })
      return;
    }
    var pageIndex = this.data.pageIndex;
    if (pageIndex != 4) {
      this.setData({
        pageIndex: 4
      })
      this.go(0);
    }
  },
  //跳转我的
  skipMy: function() {
    var user = app.globalData.user;
    if (user == null) {
      wx.showToast({
        title: '正在登陆',
        icon: 'loading',
        duration: 1000
      })
      return;
    }
    var pageIndex = this.data.pageIndex;
    if (pageIndex != 5) {
      this.setData({
        pageIndex: 5
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    }
  },
  //警告框
  toastConfirm: function(e) {
    var that = this;
    var event = e.detail.currentTarget.dataset.event;
    if (event == 'loginErr') {
      this.userLogin();
      this.setData({
        loginErrHidden: true
      })
    } else if (event == 'locationError') {
      this.setData({
        locationErrHidden: true
      })
      wx.navigateTo({
        url: '/pages/userInfo/userInfo',
      })
    }
  },



  //获取喵文动态
  getTalk: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getTalkList',
      data: {
        time: that.data.time
      },
      method: 'GET',
      success: function(r) {
        var data = r.data.data;
        if (data.length == 0) {} else {
          //左边数组
          var arr1 = [];
          //右边数组
          var arr2 = [];
          for (var i = 0; i < data.length; i++) {
            //转换数字
            data[i].likeQuantity = util.formatQuantity(data[i].likeQuantity);
            //找到图片高度
            data[i].imageHeight = util.getImageHeight(data[i].height, data[i].width, 0.48);
            //如果是视频,则取视频封面
            if (data[i].talkType != 0) {
              data[i].src = data[i].src + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_" + data[i].width + ",h_" + data[i].height + ",m_fast";
            }
            //如果是双数则放到第一个盒子
            if (i % 2 == 0) {
              arr1.push(data[i]);
            } else {
              arr2.push(data[i]);
            }
          }
          //如果是下拉则清空
          if (that.data.refresh) {
            that.setData({
              talkList: data,
              talkList1: arr1,
              talkList2: arr2,
              refresh: false
            })
            wx.stopPullDownRefresh();
          } else {
            that.setData({
              talkList: that.data.talkList.concat(data),
              talkList1: that.data.talkList1.concat(arr1),
              talkList2: that.data.talkList2.concat(arr2)
            })
          }
        }
      },
      fail: function() {
        wx.showToast({
          title: '获取日志失败,请下拉重试',
          icon: 'none',
          duration: 30000
        })
      }
    })
  },

  //是否是转发过来的
  shareSkip: function() {
    var share = this.data.share;
    if (share != null) {
      if (share.page == 'talkInfo') {
        wx.navigateTo({
          url: '/pages/talkInfo/talkInfo?id=' + share.parame.id,
        })
      }
    }
  },



  //弹出或关闭发布喵文窗口
  selectTalkType: function() {
    if (this.data.talkTypeHidden) {
      this.setData({
        talkTypeHidden: false
      })
    } else {
      this.setData({
        talkTypeHidden: true
      })
    }
  },
  //发布视频
  uploadVideo: function() {
    wx.navigateTo({
      url: '/pages/uploadTalkVideo/uploadTalkVideo',
    })
  },
  //发布图片
  uploadImage: function() {
    wx.navigateTo({
      url: '/pages/uploadTalkImage/uploadTalkImage',
    })
  },
  //粉丝关注列表
  fansList: function() {
    this.setData({
      fansDot: true
    })
    wx.navigateTo({
      url: '/pages/fansList/fansList',
    })
  },

  //获赞列表
  likeList: function() {
    this.setData({
      likeDot: true
    })
    wx.navigateTo({
      url: '/pages/likeList/likeList',
    })
  },
  //评论列表
  commentList: function() {
    this.setData({
      commentDot: true
    })
    wx.navigateTo({
      url: '/pages/commentList/commentList',
    })
  },
  //添加宠物
  addPet: function() {
    wx.navigateTo({
      url: '/pages/addPet/addPet?sequence=1',
    })
  },
  //切换宠物
  switchPet: function() {
    wx.navigateTo({
      url: '/pages/switchPet/switchPet',
    })
  },
  //删除 自己发布的日志或者送养
  drop: function(e) {
    wx.showLoading({
      title: '正在删除',
      mask: true
    })
    var type = e.detail.currentTarget.dataset.type;
    var id = e.detail.currentTarget.dataset.id;
    if (type == 'give') {
      this.deleteGiveById(id);
    } else {
      this.deleteTalkById(id);
    }
  },
  //删除送养
  deleteGiveById: function(id) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'deleteGiveById',
      data: {
        id: id,
        userId: app.globalData.user.id
      },
      success: function(r) {
        if (r.data.code == 200) {
          that.setData({
            refresh: true
          })
          that.getGiveListByUserId();
        } else {
          wx.showToast({
            title: '删除送养记录失败',
            icon: 'none',
            duration: 30000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,删除送养记录失败',
          icon: 'none',
          duration: 30000
        })
      },
      complete: function() {
        wx.hideLoading();
      }
    })
  },
  //删除日志
  deleteTalkById: function(id) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'deleteTalk',
      data: {
        id: id,
        userId: app.globalData.user.id
      },
      success: function(r) {
        if (r.data.code == 200) {
          that.setData({
            refresh: true
          })
          that.getTalkListByUserId();
        } else {
          wx.showToast({
            title: '删除日志记录失败',
            icon: 'none',
            duration: 30000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,删除送养日志失败',
          icon: 'none',
          duration: 30000
        })
      },
      complete: function() {
        wx.hideLoading();
      }
    })
  },
  //商品列表
  getGoodsList: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + '/getGoodsList',
      success: function(r) {
        if (r.data.code == 200) {
          var goodsList = r.data.data;
          for (var i of goodsList) {
            i.goodsId = i.specList[0].goodsId;
            i.price = i.specList[0].price;
            i.specId = i.specList[0].specId;
            i.specName = i.specList[0].specName;
            for (var x of i.specList) {
              if (x.price < i.price) {
                i.goodsId = x.goodsId;
                i.price = x.price;
                i.specId = x.specId;
                i.specName = x.specName;
              }
            }
          }
          that.setData({
            goodsList: goodsList
          })
        } else {
          wx.showToast({
            title: '获取商品失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络连接断开，获取商品失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //跳转送养
  giveNav: function() {
    wx.navigateTo({
      url: '/pages/giveList/giveList',
    })
  },
  //跳转购物车
  showppingCarNav: function() {
    wx.navigateTo({
      url: '/pages/shoppingCar/shoppingCar',
    })
  },
  //获取购物车商品
  getShoppingCarList: function() {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'getShoppingCarList',
      data: {
        userId: app.globalData.user.id
      },
      success: function(r) {
        if (r.data.code == 200) {
          app.globalData.shoppingCarList = r.data.data;
          that.setData({
            shoppingCarQuantity: r.data.data.length
          })
        } else {
          wx.showToast({
            title: '获取购物车商品失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,获取购物车商品失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  //添加或更改
  updateOrAddShoppingCar: function(e) {
    var specId = e.currentTarget.dataset.specid;
    var goodsId = e.currentTarget.dataset.goodsid;
    var shoppingCar = app.globalData.shoppingCarList;
    for (var i of shoppingCar) {
      if (i.specId == specId) {
        var quantity = parseInt(i.quantity) + 1;
        this.updateGoodsQuantity(goodsId, quantity, specId);
        return;
      }
    }
    this.addShoppingCar(goodsId, specId);
  },

  //添加商品到购物车
  addShoppingCar: function(id, specId) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'addGoods',
      data: {
        userId: app.globalData.user.id,
        goodsId: id,
        quantity: 1,
        spec: specId
      },
      method: 'POST',
      success: function(r) {
        if (r.data.code == 200) {
          app.globalData.shoppingCarList = r.data.data;
          that.setData({
            shoppingCarQuantity: r.data.data.length
          })
        } else {
          wx.showToast({
            title: '加入购物车失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,加入购物车失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  //更改购物车商品数量
  updateGoodsQuantity: function(id, quantity, specId) {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl + 'updateGoodsQuantity',
      data: {
        userId: app.globalData.user.id,
        goodsId: id,
        quantity: quantity,
        spec: specId
      },
      method: 'POST',
      success: function(r) {
        if (r.data.code == 200) {
          app.globalData.shoppingCarList = r.data.data;
          that.setData({
            shoppingCarQuantity: r.data.data.length
          })
        } else {
          wx.showToast({
            title: '加入购物车失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络断开连接,加入购物车失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //商品详情
  goodsInfo: function(e) {
    var index = e.currentTarget.dataset.index;
    var goodsId = this.data.goodsList[index].id;
    wx.navigateTo({
      url: '/pages/goodsInfo/goodsInfo?goodsId=' + goodsId,
    })
  },
  //打开选项卡
  openFlank: function() {
    this.setData({
      flankHidden: !this.data.flankHidden
    })
  },
  //前往收货地址
  shoppingAddress:function(){
    wx.navigateTo({
      url: '/pages/shoppingAddress/shoppingAddress',
    })
  },
  //投诉建议
  suggest:function(){
    wx.navigateTo({
      url: '/pages/suggest/suggest',
    })
  }
})